#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : BatteryPi
# @Time    : 2020/12/22 19:24
# @Author  : wp
# @File    : serialcmdtools.py
# @Software: PyCharm

import sys
import serial
import time
import traceback
import re
from utils import logutils, dtutils

logger = logutils.getlogger(__file__)

ser = None


#####################################################
#################串口部分############################
####################################################
def init():
    global ser
    try:
        ser = serial.Serial("/dev/ttyAMA0", 9600, timeout=2)
        if not ser:
            raise serial.SerialException("打开串口错误")
        if not ser.isOpen():
            ser.open()
        logger.info("com:" + ser.name + " opened")
        # ser.write("test\n".encode("utf-8"))
        # time.sleep(0.1)
        # resbytes = ser.readline()
        # resstr = resbytes.decode().strip()
        # logger.debug(resstr)
        # if resstr != "test":
        #     raise serial.SerialException("test返回异常！")
    except serial.SerialTimeoutException as e1:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return
    except serial.SerialException as e2:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return
    except Exception as e3:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return


# 关闭串口
def destroy():
    global ser
    if ser and ser.isOpen:
        ser.close()
        logger.info('com closed')


# 发送串口命令
def sendTest():
    logger.debug("=================== sendTest ===================")
    cmdstr = "test\n"
    if cmdstr[-1] != '\n':
        cmdstr = cmdstr + "\n"
    logger.info("cmdstr={}".format(cmdstr).replace("\n", "\\n"))
    cmdbytes = cmdstr.encode("utf-8")
    ser.write(cmdbytes)
    time.sleep(0.1)
    reslst = []
    for _ in range(3):
        resbytes = ser.readline()
        resstr = resbytes.decode().strip()
        logger.info(resstr)
        reslst.append(resstr)
    return reslst


# 发送串口命令
def sendCmd(cmdstr="test\n"):
    logger.debug("=================== sendCmd ===================")
    if cmdstr[-1] != '\n':
        cmdstr = cmdstr + "\n"
    logger.info("cmdstr={}".format(cmdstr).replace("\n", "\\n"))
    cmdbytes = cmdstr.encode("utf-8")
    ser.write(cmdbytes)
    time.sleep(0.1)
    reslst = []
    for _ in range(3):
        resbytes = ser.readline()
        resstr = resbytes.decode().strip()
        if len(resstr) == 0:
            break
        logger.info(resstr)
        reslst.append(resstr)
    return reslst


def exeCmd(cmdlst=[]):
    logger.info(" ".join(cmdlst))
    cmdtype = cmdlst[0].strip()
    if cmdtype in ["test", "readAlarmInfo", "setalarmmode_nosleep","readVolt","readCurrent","readVoltCurrent","setalarmmode_lowpower", "getalarmmode", "readTime",
                   "readAlarm", "enableAlarm"]:
        print(cmdtype)
        reslst=sendCmd(cmdtype)
        logger.info("\n".join(reslst))
    if cmdtype in ["setStartTime", "setEndTime", "setAlarm"]:
        params = " ".join(cmdlst[1:]).strip()
        if re.match(r"^(\d{2}):(\d{2})$", params):
            cmdstr = " ".join(cmdlst).strip()
            print(cmdstr)
            logger.info("cmdstr={}".format(cmdstr))
            reslst = sendCmd(cmdstr)
            logger.info("\n".join(reslst))
        else:
            logger.error(cmdtype + "参数错误！")
    if cmdtype in ["setTime", "setTimeNoAlarm"]:
        params = " ".join(cmdlst[2:]).strip()
        if re.match(r"^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$", params):
            cmdstr = " ".join(cmdlst).strip()
            logger.info("cmdstr={}".format(cmdstr))
            reslst = sendCmd(cmdstr)
            logger.info("\n".join(reslst))
        else:
            logger.error(cmdtype + "参数错误！")
    if cmdtype=="synTime":
        cmdstr="setTime {}".format(dtutils.currentTimeStamp())
        print(cmdstr)
        reslst = sendCmd(cmdstr)
        logger.info("\n".join(reslst))
    if cmdtype=="synTimeNoAlarm":
        cmdstr="setTimeNoAlarm {}".format(dtutils.currentTimeStamp())
        print(cmdstr)
        reslst = sendCmd(cmdstr)
        logger.info("\n".join(reslst))




if __name__ == '__main__':
    init()
    exeCmd(sys.argv[1:])
    destroy()
